import React from 'react'
import {NavLink} from 'react-router-dom'
import Nav from '../../../components/nav'
import {get} from '../../../axios'

const get_option = (role, options) => {
    get(`/mem/project-count/${role}`).then(resp=> {
        console.log(resp.data)
        if (!resp.data[0]) {
            return ;
        } else {

        let {total} = resp.data.reduce( (a, b) => {
            let c = {total: 0}
            c.total = a.total + b.total
            return c
        } )
        resp.data.map(x => {
            options.forEach(function(ele) {
                if (ele.value === '') {
                    ele.total = total
                } else if (ele.value===x.status) {
                    ele.total = x.total
                }
            })
        })
    }
        
    })
    console.log(options)
    return options
}
const publishStatusOption = [
    {label: '全部', value: '', type: 'status'}, 
    {label: '草稿', value: 'draft', type: 'status'}, 
    {label: '待分配', value: 'publish', type: 'status'}, 
    {label: '投标中', value: 'pending', type: 'status'}, 
    {label: '执行中', value: 'working', type: 'status'},
    {label: '已完成', value: 'done', type: 'status'},
    
],
    executeStatusOption = [
        {label: '全部', value: '', type: 'status'}, 
        {label: '投标中', value: 'pending', type: 'status'}, 
        {label: '进行中', value: 'working', type: 'status'},
        {label: '已拒绝', value: 'reject', type: 'status'},
        {label: '已取消', value: 'cancel', type: 'status'}, 
        {label: '已完成', value: 'done', type: 'status'}, 
        {label: '已被抢', value: 'drop', type: 'status'}, 
    ],
    sortOption = [
        {label: '按时间顺序', value: 'created_at', type: 'sort', order: 'asc'}, 
        {label: '按时间倒序', value: 'created_at', type: 'sort', order: 'desc'}, 
        {label: '按项目名称顺序', value: 'title', type: 'sort', order: 'asc'},
        {label: '按项目名称倒序', value: 'title', type: 'sort', order: 'desc'}
    ]

export const PLHOC = (PLComponent) => 
    class Layout extends React.Component {
        constructor(props) {
            super(props)
            this._height = 0
            this.state = {
                searchVisible: false,
                visible: false,
                type: 'status',
                conditions: [],
                red_dot: {}
            }
        }

        componentDidMount() {
            let search = ''
            if (localStorage.getItem('conditions')) {
                this.setState({conditions: JSON.parse(localStorage.getItem('conditions'))})
                search = this.resolveSearch(JSON.parse(localStorage.getItem('conditions')))
            }
            get(`mem/project-my-publish?page=1${search}`).then(resp=>{
                if (resp.data.filter(x=>x.is_show_red_dot)[0]) {
                    this.setState({red_dot: {...this.state.red_dot, publish: true}})
                }
            })

            get(`mem/project-my-grab?page=1${search}`).then(resp=>{
                if (resp.data.filter(x=>x.project.is_show_red_dot)[0]) {
                    this.setState({red_dot: {...this.state.red_dot, grab: true}})
                }
            })

            get(`mem/project-my-execute?page=1${search}`).then(resp=>{
                if (resp.data.filter(x=>x.project.is_show_red_dot)[0]) {
                    this.setState({red_dot: {...this.state.red_dot, execute: true}})
                }
            })
        }

        componentDidUpdate() {
            this.updateHeight()
        }

        updateHeight() {
            // let winH = window.innerHeight,
            //     divTop = document.getElementsByClassName('am-list-view-scrollview')[0].getBoundingClientRect().top,
            //     divH = document.getElementsByClassName('am-list-view-scrollview')[0].clientHeight,
            //     divZ = winH - divTop - 127
            
            // if ( this._height == 0) {
            //     this._height = divH
            // }
            // divH > divZ ? document.getElementsByClassName('am-list-view-scrollview')[0].style.height = divZ+"px" : 
            //     document.getElementsByClassName('am-list-view-scrollview')[0].style.height = this._height+"px"
        }
        resolveSearch = (conditions) => {
            let search = ''
            conditions.forEach( (ele) => {
                if (ele.type=='sort') {
                    search += `&sortKey=${ele.value}&sortValue=${ele.order}`
                } else {
                    search += `&${ele.type}=${ele.value}`
                }
            })
            return search
        }
        renderTabTitle() {
            const red_dot = this.state.red_dot
            return (
                <div class="row text-center nav">
                    <NavLink to='/my-project/publish' activeClassName="first" exact className={red_dot.publish?"red-dot col-xs-4":'col-xs-4'} replace={true}>
                    我发布的
                    </NavLink>
                    <NavLink to='/my-project/grab' activeClassName="first" exact className={red_dot.grab?"red-dot col-xs-3":'col-xs-3'} replace={true}>
                    我抢单的
                    </NavLink>
                    <NavLink to='/my-project/execute' activeClassName="first" exact className={red_dot.execute?"red-dot col-xs-3":'col-xs-3'} replace={true}>
                    我执行的
                    </NavLink>
                    <i onClick={this.triggerSearchBarShow} className='iconfont icon-sousuo col-xs-2'></i>
                </div>
            )
        }

        triggerSearchBarShow = () => {
            this.setState({searchVisible: !this.state.searchVisible})
        }

        triggerOptionShow = (type=null) => {
            this.setState({visible: !this.state.visible, type})
        }
        
        handSelect = (c) => {
            this.setState({visible: false})
            let { conditions } = this.state,
            flag = false,
            newConditions = []
            if (conditions[0]) {
                newConditions = conditions.map( x => {
                    if (x.type == c.type ) {
                        flag = true
                        return c
                    } else {
                        return x
                    }
                }) 
            } else {
                flag = true
                newConditions = [c]
            }
            
            newConditions = flag ? newConditions : [...newConditions, c]
            localStorage.setItem('conditions', JSON.stringify(newConditions))
            this.setState({conditions: newConditions})
        }

        reslove_options = (type, role) => {
            if (type == 'status') {
                if (role == 'publish') {
                    return get_option('publish', publishStatusOption)
                } else if (role=='execute') {
                    return get_option(role, executeStatusOption)
                } else {
                    return []
                }
            } else {
                return sortOption
            }
        }

        render() {
            const {type, visible, searchVisible} = this.state,
                  role = window.location.href.split('/').pop(),
                  options = this.reslove_options(type, role)
                  
           const conditions = localStorage.getItem('conditions') ? 
           JSON.parse(localStorage.getItem('conditions')) : this.state.conditions
            // console.log(conditions)
            return (
                <React.Fragment>
                    <div className="container">
                        <div className="box">
                            <div class="Ibox clearfix">
                                {this.renderTabTitle()}
                            </div>

                            <div className="row co-option" style={{display: searchVisible?'block':'none'}}>
                                <div className='col-xs-6' onClick={()=>this.triggerOptionShow('status')}>
                                    {conditions.filter( x => x.type=='status').pop()?
                                    conditions.filter( x => x.type=='status').pop().label:'项目状态'}
                                </div>
                                <div className='col-xs-6' onClick={()=>this.triggerOptionShow('sort')}>
                                    {conditions.filter( x => x.type=='sort').pop()?
                                    conditions.filter( x => x.type=='sort').pop().label:'排序'}
                                </div>
                            </div>

                            {/* 筛选层 */}
                            {
                                searchVisible&&visible ? 
                                <ul className='option-box'>
                                    {options.map( x => 
                                        <li onClick={()=>this.handSelect(x)}>
                                        <p>{x.label}
                                            {x.type==='status'? `（${x.total||0}）`: null}
                                        </p></li>
                                    )}
                                </ul>
                                : null
                            }
                            
                            <PLComponent {...this.props} conditions={conditions}/>
                            
                        </div>
                    </div>
                    <Nav/>
                </React.Fragment>
            )
        }
    }
